package sbc.ms.gui;

import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Container;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.xvsm.api.core.Capi;
import org.xvsm.api.core.ContainerRef;
import org.xvsm.api.core.CoordinationTypes;
import org.xvsm.api.core.Entry;
import org.xvsm.api.core.Tuple;
import org.xvsm.api.core.notification.NotificationID;
import org.xvsm.api.core.notification.NotificationListener;
import org.xvsm.client.ClientCapi;

import sbc.model.Platine;
import sbc.model.Sensor;
import sbc.ms.Consumer;
import sbc.ms.Producer;
import sbc.ms.Taker;
import sbc.ms.Util;


public class PlatinenFabrik
    extends JFrame implements ActionListener, WindowListener, NotificationListener
{
    // GUI
    private TextField idTextField; 
    private TextArea textArea;
    private CheckboxGroup cbg;
    //private JPanel panel;    

    private Container container;
    
    // MS
    private String url;
    private Capi capi;
    private ContainerRef cref;
    private List<Entry> elements;


    public PlatinenFabrik (String url) {
        System.out.println (url + " init");
        this.url = url;
        
		this.capi = new ClientCapi(url);
		this.capi.init(false);
        addListener(this);

        container = getContentPane();
        setTitle ("PlatinenFabrik @ " + url);
        setLocation (0, 0);
        setSize (800, 400);
        
        try {
            /*
             * connect to MS and get container
             */
			Logger.getLogger("org.xvsm.client").setLevel(Level.WARN);
			capi = new ClientCapi(url);
			capi.init(false);
			
			cref = Util.getOrCreateNamedContainer(capi, "Container", CoordinationTypes.FIFO);
			System.out.println("CREF: " + cref);
            System.out.println ("Connect ok");
           
            /*
             * read first entry from FIFO stack
             
            System.out.println ("get first entry from FIFO stack:");
            List<Entry> read = capi.read(cref);
            Tuple t = (Tuple) read.get(0);
			elements = t.getValue();
	
			System.out.println(elements.get(0).getValue() + " "
				+ elements.get(1).getValue());
			*/	
        } 
        catch (Exception e) {
            System.out.println ("Exception: " + e);
            e.printStackTrace ();
            System.exit (-10);
        }
        
        JPanel panel = new JPanel();
        cbg = new CheckboxGroup();
        panel.add(new Checkbox("Platine", cbg, true));
        panel.add(new Checkbox("Sensor", cbg, false));
        
        idTextField = new TextField("",20);     
        panel.add(idTextField);
        
        JButton okButton = new JButton("Add");

        panel.add(okButton);
        addButtonListener(okButton);
        
        textArea = new TextArea();
        panel.add(textArea);
        
        container.add(panel);

        /*
        for (int i = 0; i < entries.size(); i++)
        {
            JPanel panel = new JPanel ();
            panel.setLayout (new GridLayout (1, 3));

            System.out.println (i + ".Landebahn Oid = " + 
                                (CorsoVarOid) v.get (i));
            Landebahn lb = new Landebahn ((CorsoVarOid) v.get (i));
        
            // landebahnNr Text Field
            landebahnNrTextFields[i] = new TextField ("" + i);     
            landebahnNrTextFields[i].setFont (new Font (null, Font.PLAIN, 24));  // null = use default font name
            panel.add (landebahnNrTextFields[i]); 
            
            // status Text Field
            statusTextFields[i] = new TextField (lb.getStatus ());     
            statusTextFields[i].setFont (new Font (null, Font.PLAIN, 24));       // null = use default font name
            panel.add (statusTextFields[i]); 
            
            // flugNr Text Field
            flugNrTextFields[i] = new TextField (lb.getFlugNr ());     
            flugNrTextFields[i].setFont (new Font (null, Font.PLAIN, 24));       // null = use default font name
            panel.add (flugNrTextFields[i]);


            container.add (panel);
        }
    	*/
        
        addWindowListener (this);   
        setVisible (true); 
    }



    /**==================================================================== 
     * ACTION EVENT HANDLER functions  
     *=====================================================================*/  
    public void actionPerformed (ActionEvent e) {
        System.out.println ("GUI: actionPerformed: Event Fired: " + e.getActionCommand ());
    }


    private void addButtonListener(JButton b) {
        b.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent ae) {
            	System.out.println ("GUI: actionPerformed: Button clicked: " +
            		ae.getActionCommand ());
            	
            	if (cbg.getSelectedCheckbox().getLabel().equals("Platine")) {
	            	Platine myPlatine1= new Platine();
	        		myPlatine1.setMyId(idTextField.getText());
	        		
	        		Producer p = new Producer(url, myPlatine1);
	        		p.start();
            	}
            	else if (cbg.getSelectedCheckbox().getLabel().equals("Sensor")) {
	        		Sensor mySensor = new Sensor();
	        		mySensor.setMyId(idTextField.getText());
	        		
	        		Producer p = new Producer(url, mySensor);
	        		p.start();
            	}
            }
        });
    }
    

    /**==================================================================== 
     * NOTIFICATION HANDLER functions  
     *=====================================================================*/  
	public void sendNotification(NotificationID id, List<Entry> entries) {
		System.out.println("Notification fired: " + id + " - " + entries);
		
		Tuple t = (Tuple) entries.get(0);
		elements = t.getValue();

		System.out.println(elements.get(0).getValue() + " "
			+ elements.get(1).getValue());
		
		textArea.append(elements.get(0).getValue() + " "
			+ elements.get(1).getValue() + "\n");
			
		/*
		JPanel panel = new JPanel();
		
        TextField textField1 = new TextField((String)elements.get(0).getValue());    
        panel.add(textField1);
        
        TextField textField2 = new TextField((String)elements.get(1).getValue());     
        panel.add(textField2);
        getContentPane().add(panel);
        //container.add(panel.r);
        //panel.repaint();
        container.repaint();
		//entriesTextField.setText(id.toString());
		*/		
	}
	
	public void sendNotification(NotificationID id) {
		System.out.println("Notification fired: " + id);
		//entriesTextField.setText(id.toString());
	}
	
	public void addListener(NotificationListener listener) {
		Consumer c = new Consumer(url, listener);
		c.start();
		/*
		try {			
			ContainerRef cref = Util.getOrCreateNamedContainer(capi,
					"Container", CoordinationTypes.FIFO);
			System.out.println("CREF: " + cref);

			capi.createNotification(cref, -1, NotificationTarget.ANY.code(),
					NotificationMode.INFINITE, true,
					listener);
		} 
		catch (Exception e) {
			e.printStackTrace();
		}*/
	}    


    /**==================================================================== 
     * further ACTION EVENT HANDLER functions  
     *=====================================================================*/  
    public void windowClosing (WindowEvent e) { System.exit (0); }
    public void windowClosed (WindowEvent e) {}  
    public void windowOpened (WindowEvent e) {}   
    public void windowIconified (WindowEvent e) {} 
    public void windowDeiconified (WindowEvent e) {}
    public void windowActivated (WindowEvent e) {}  
    public void windowDeactivated (WindowEvent e) {}     


    /**==================================================================== 
     * MAIN
     *=====================================================================*/  
    public static void main (String [] args)  {
        if (args.length < 1) {
            System.out.println ("CALL: PlatinenFabrik <url>");
            System.exit (-1);
        }
        new PlatinenFabrik (args[0]);
    }
}
